package com.app.micaihu.view.comment.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.text.Html;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.AppBaseAdapter;
import com.app.micaihu.base.BaseOldActivity;
import com.app.micaihu.bean.comment.ChildComment;
import com.app.micaihu.bean.comment.NormalComment;
import com.app.micaihu.bean.speak.ICommentEntity;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.utils.CommentUtils1;
import com.app.micaihu.utils.ImageLoadUtils;
import com.app.micaihu.utils.InteractiveUtils;
import com.app.micaihu.utils.StatServiceUtils;
import com.app.micaihu.view.army.activity.ArmyDetailActivity;
import com.app.micaihu.view.army.activity.ArmyMedalListActivity;
import com.app.micaihu.view.comment.SecondaryCommentDetailActivity;
import com.app.micaihu.view.comment.SubmitCommentListener;
import com.app.micaihu.view.newsdetail.VideoDetailActivity;
import com.app.micaihu.view.user.userinfo.activity.MyHomepageDynamicActivity;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.app.utils.util.view.expression.view.BiaoQinTextView;
import com.blankj.utilcode.util.ActivityUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Guo on 2016/12/18.
 * <p>
 * <p>
 * 一级评论的适配器
 */

public class NormalCommentAdapter extends AppBaseAdapter<NormalComment> implements View.OnClickListener, View.OnLongClickListener {

    public String replyColor;//回复颜色
    public int currentLastHotIndex;//当前最后一个热门评论的下标

    private NormalComment currentReplyEntity = null;
    private SubmitCommentListener commentListener;
    private boolean comment = true;
    private OnItemOpratedListener onItemOpratedListener;

    public NormalCommentAdapter(List<NormalComment> list, Context context) {
        this(list, context, true);


    }

    public NormalCommentAdapter(List<NormalComment> list, Context context, boolean comment) {
        super(list, context);
        replyColor = "#546a93";
        this.comment = comment;
    }


    @Override
    public int getViewTypeCount() {
        return 3;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return list != null && !list.isEmpty() ? list.size() : 0;
    }

    @Override
    public int getItemViewType(int position) {
        ICommentEntity iCommentEntity = list.get(position);
        if (iCommentEntity == null) {
            return 0;
        }
        if (!TextUtils.isEmpty(iCommentEntity.getICommentTitle())) {
            return 1;
        } else {
//            if(InteractiveUtils.getInstance().theDefriendIsContains(iCommentEntity.getIToUid())){
//                return 3;
//            }
            return 2;
        }
    }


    @Override
    public View creatView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        int type = getItemViewType(position);
        if (convertView == null) {

            if (type == 2) {
                convertView = inflater.inflate(R.layout.item_news_comment, null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            } else if (type == 1) {
                convertView = inflater.inflate(R.layout.layout_driver_title_margin, null);
                ((TextView) (convertView.findViewById(android.R.id.text2))).setText(list.get(position).getICommentTitle());
                return convertView;
            } else {
                convertView = inflater.inflate(R.layout.item_layout_gone, null);
                return convertView;
            }
        } else {
            if (type == 2) {
                viewHolder = (ViewHolder) convertView.getTag();
            } else if (type == 1) {
                ((TextView) (convertView.findViewById(android.R.id.text2))).setText(list.get(position).getICommentTitle());
                return convertView;
            } else {
                return convertView;
            }
        }
//        ICommentEntity iCommentEntity = list.get(position);
        NormalComment iCommentEntity = list.get(position);

        if (iCommentEntity == null) {
            return convertView;
        }


        //去掉精彩评论和最新评论间的下划线
        if (position == currentLastHotIndex) {
            viewHolder.lineview.setVisibility(View.INVISIBLE);
        } else if (viewHolder.lineview.getVisibility() == View.INVISIBLE) {
            viewHolder.lineview.setVisibility(View.VISIBLE);
        }
        viewHolder.parentLayout.setTag(R.id.tag_first, iCommentEntity);//设置数据标识
        viewHolder.replyLayout.setTag(iCommentEntity);//设置数据标识
        viewHolder.readAllText.setTag(iCommentEntity);
        viewHolder.userImg.setTag(iCommentEntity);
        viewHolder.userName.setTag(iCommentEntity);


        //TODO 暂时替代 评论列表卡顿
        LoadImageUtils.getInstance().loadListCircleImage(viewHolder.userImg, iCommentEntity.getIHeadPic());

        ImageLoadUtils.loadImage(iCommentEntity.getIRankIcon(), viewHolder.userRank);
        if (com.blankj.utilcode.util.StringUtils.isEmpty(iCommentEntity.getHonourPic())) {
            viewHolder.ivHonourPic.setVisibility(View.GONE);
        } else {
            viewHolder.ivHonourPic.setVisibility(View.VISIBLE);
            ImageLoadUtils.loadImage(iCommentEntity.getHonourPic(), viewHolder.ivHonourPic);
        }
        viewHolder.tvArmyGroupInfo.setText(iCommentEntity.getArmyGroupInfo());
        viewHolder.userName.setText(iCommentEntity.getINickName());
        viewHolder.rankname.setText(iCommentEntity.getIRankName());
        viewHolder.commentTime.setText(iCommentEntity.getIPublishTime());
        viewHolder.commentZan.setText(TextUtils.isEmpty(iCommentEntity.getILaudNum()) || iCommentEntity.getILaudNum().equals("0") ? "" : iCommentEntity.getILaudNum());

        viewHolder.message.setPicText(iCommentEntity.getIContent());

        viewHolder.ivHonourPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!com.blankj.utilcode.util.StringUtils.isEmpty(iCommentEntity.getUid())) {
                    Intent intent = new Intent(context, ArmyMedalListActivity.class);
                    intent.putExtra(Config.Extra.toUid, iCommentEntity.getUid());
                    ActivityUtils.startActivity(intent);
                }
            }
        });
        viewHolder.tvArmyGroupInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!com.blankj.utilcode.util.StringUtils.isEmpty(iCommentEntity.getUid()) && !com.blankj.utilcode.util.StringUtils.isEmpty(iCommentEntity.getGid())) {
                    Intent intent = new Intent(context, ArmyDetailActivity.class);
                    intent.putExtra(Config.Extra.toUid, iCommentEntity.getUid());
                    intent.putExtra(Config.Extra.id, iCommentEntity.getGid());
                    ActivityUtils.startActivity(intent);
                }
            }
        });
        float measureText = viewHolder.paint.measureText(iCommentEntity.getIContent());
        if (measureText > ViewSizeUtils.getWidthPixels() * 8) {
            viewHolder.readAllText.setVisibility(View.VISIBLE);
        } else {
            viewHolder.readAllText.setVisibility(View.GONE);
        }
        //判断是否点赞过
        if (InteractiveUtils.getInstance().theLaudIsContains(iCommentEntity.getICommentId(), true)) {
            viewHolder.commentZan.setEnabled(false);
            viewHolder.laudContainer.setTag(true);
        } else {
            viewHolder.commentZan.setEnabled(true);
            viewHolder.laudContainer.setTag(iCommentEntity);
        }
        //判断有没有子回复
        List<ChildComment> iChildList = list.get(position).getIChildList();
        if (iChildList != null && iChildList.size() != 0) {
            viewHolder.replyLayout.removeAllViews();
            String reply_str;
            for (int i = 0; i < iChildList.size(); i++) {
                ChildComment childComment = iChildList.get(i);
                if (childComment == null || InteractiveUtils.getInstance().theDefriendIsContains(childComment.getUid())) {
                    continue;
                }

                BiaoQinTextView textView = new BiaoQinTextView(context);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                if (i != iChildList.size() - 1) {
                    layoutParams.setMargins(0, 0, 0, 10);
                }
                textView.setLayoutParams(layoutParams);
                textView.setLineSpacing(4.3f, 1.1f);
                textView.setMaxLines(3);
                textView.setEllipsize(TextUtils.TruncateAt.END);
                textView.setTextSize(15f);
                textView.setTextColor(context.getResources().getColor(R.color.comment_reply_msg));
                if (TextUtils.equals(childComment.getType(), TypeConstant.COMMENT_TWO)) {
                    reply_str = "<font color='" + replyColor + "' >" + childComment.getNickName() + ": @" + childComment.getpNickName() + " </font>" + childComment.getContent();
                } else {
                    reply_str = "<font color='" + replyColor + "' >" + childComment.getNickName() + ": </font>" + childComment.getContent();
                }
                textView.setPicText(Html.fromHtml(reply_str));
                viewHolder.replyLayout.addView(textView);
            }

            if (viewHolder.replyLayout.getChildCount() == 0 && StringUtils.toInt(iCommentEntity.getIChildNum(), 0) <= 3) {
                viewHolder.replyLayout.setVisibility(View.GONE);
            } else {
                viewHolder.replyLayout.setVisibility(View.VISIBLE);
            }

            if (StringUtils.toInt(iCommentEntity.getIChildNum(), 0) > 3) {
                TextView moreview = new TextView(context);
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

                if (viewHolder.replyLayout.getChildCount() > 0) {
                    layoutParams.setMargins(0, 15, 0, 0);

                } else if (viewHolder.replyLayout.getChildCount() == 0) {
                    layoutParams.setMargins(0, 0, 0, 0);
                }
                moreview.setLayoutParams(layoutParams);
                moreview.setTextSize(12f);
                moreview.setTextColor(context.getResources().getColor(R.color.common_font_color_8));
                moreview.setText(AppApplication.getInstance().getString(R.string.common_all_comment, iCommentEntity.getIChildNum()));
                viewHolder.replyLayout.addView(moreview);
            }

        } else {
            viewHolder.replyLayout.setVisibility(View.GONE);
        }

        return convertView;
    }

    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.comment_usericon:
            case R.id.comment_username:
                if (v.getTag() != null && v.getTag() instanceof NormalComment) {
                    this.currentReplyEntity = (NormalComment) v.getTag();
                    try {
                        MyHomepageDynamicActivity.goToUserHomePage((Activity) context, currentReplyEntity.getIToUid());

                    } catch (Exception e) {

                    }
                }

                break;
            case R.id.fl_laud_container:
                InteractiveUtils.getInstance().laud((FrameLayout) v, null);
                break;
            case R.id.comment_parentlayout:
                StatServiceUtils.event(Config.EventBauduId.teamcomment_click, "军团详情_用户评论点击");
                if (v.getTag(R.id.tag_first) instanceof NormalComment && v.getTag(R.id.tag_first) != null) {
                    this.currentReplyEntity = (NormalComment) v.getTag(R.id.tag_first);
                    goToSecondaryDetail();
                }
                break;
            case R.id.reply://菜单回复
                StatServiceUtils.event(Config.EventBauduId.teamlongpress_comment, "军团详情_长按评论");
                InteractiveUtils.getInstance().dimissCommentPop();
                replyComment();
                break;
            case R.id.jubao://菜单举报
                StatServiceUtils.event(Config.EventBauduId.teamlongpress_report, "军团详情_长按举报");
                InteractiveUtils.getInstance().dimissCommentPop();
                InteractiveUtils.getInstance().report(v, currentReplyEntity, comment);
                break;
            case R.id.fuzhi://菜单复制
                StatServiceUtils.event(Config.EventBauduId.teamlongpress_copy, "军团详情_长按复制");
                InteractiveUtils.getInstance().dimissCommentPop();
                InteractiveUtils.getInstance().copy(currentReplyEntity);
                break;
            case R.id.delete://删除评论
                InteractiveUtils.getInstance().dimissCommentPop();
                deleteComment();
                break;

            case R.id.comment_readall://查看全文
//            case R.id.comment_reply_layout://查看回复

                if (v.getTag() instanceof NormalComment && v.getTag() != null) {
                    currentReplyEntity = (NormalComment) v.getTag();
                }

                goToSecondaryDetail();
                break;
        }

    }


    /**
     * 去往次级评论
     */
    private void goToSecondaryDetail() {
        if (currentReplyEntity != null) {
            Intent intent = new Intent(context, SecondaryCommentDetailActivity.class);
            intent.putExtra(Config.Extra.PARAMETER1, currentReplyEntity.getNewsId());
            intent.putExtra(Config.Extra.PARAMETER2, currentReplyEntity.getICommentId());
            intent.putExtra(SecondaryCommentDetailActivity.COMMENT_OR_POST, comment);
            ((Activity) context).startActivityForResult(intent, Config.ResultCode.REQUESTCODE_1);
        }

    }


    @Override
    public boolean onLongClick(View v) {
        if (v == null) return false;
        switch (v.getId()) {
            case R.id.comment_parentlayout:
                if (v.getTag(R.id.tag_first) instanceof NormalComment && v.getTag(R.id.tag_first) != null) {
                    StatServiceUtils.event(Config.EventBauduId.teamcomment_longpress, "军团详情_用户评论长按");
                    this.currentReplyEntity = (NormalComment) v.getTag(R.id.tag_first);
                    InteractiveUtils.getInstance().showCommentPop(v, this);
                }
                return true;
        }
        return false;
    }


    public NormalComment getCurentCommentEntity() {

        return currentReplyEntity;
    }


    /**
     * 删除评论
     */
    private void deleteComment() {

        SubmitCommentListener deleteComtListener = new SubmitCommentListener() {
            @Override
            public void startSubmit() {

            }

            @Override
            public void errorSubmit(VolleyError error) {
                ToastUtils.makeText(AppApplication.getInstance().getString(R.string.common_delete_failure));
            }

            @Override
            public void successSubmit(NormalComment normalComment) {
                if (currentReplyEntity == null) {
                    return;
                }
                list.remove(currentReplyEntity);
                notifyDataSetChanged();
                if (onItemOpratedListener != null) {
                    onItemOpratedListener.onItemDeleted();
                }
            }
        };
        CommentUtils1.getInstance().showDeleteDialog((Activity) context, currentReplyEntity, deleteComtListener, !comment);
    }


    public interface OnItemOpratedListener {
        void onItemDeleted();
    }

    public void setOnItemOpration(OnItemOpratedListener onItemOpratedListener) {
        this.onItemOpratedListener = onItemOpratedListener;
    }


    /**
     * 发表评论
     */
    private void replyComment() {
        if (this.currentReplyEntity == null) {
            return;
        }
        if (commentListener == null) {
            commentListener = new SubmitCommentListener() {
                @Override
                public void startSubmit() {

                }

                @Override
                public void errorSubmit(VolleyError error) {

                }

                @Override
                public void successSubmit(NormalComment normalComment) {
                    if (currentReplyEntity == null) {
                        return;
                    }

                    List<ChildComment> iChildList = currentReplyEntity.getIChildList();
                    if (iChildList == null) {
                        iChildList = new ArrayList<ChildComment>();
                    }
                    normalComment.setType(TypeConstant.COMMENT_ONE);
                    iChildList.add(0, normalComment);
                    currentReplyEntity.setIChildList(iChildList);

                    notifyDataSetChanged();
                }
            };
        }

        CommentUtils1.getInstance().showDialog((Activity) context, null, currentReplyEntity.getNewsId(),
                currentReplyEntity, commentListener, currentReplyEntity.getNewsOrTopic(), false);


    }

    class ViewHolder {

        CustomImageView userImg;//头像
        CustomImageView userRank;//军衔
        ImageView ivHonourPic;//粉絲標志
        TextView tvArmyGroupInfo;//名称
        TextView userName;//名称
        TextView rankname;//军衔名称
        TextView commentZan;//点赞
        TextView commentTime;//发布时间
        BiaoQinTextView message;//评论内容
        LinearLayout replyLayout;//评论回复模块
        TextView readAllText;//查看全文
        View parentLayout;//父布局
        View lineview;//下划线
        FrameLayout laudContainer;//点赞 的点击

        TextPaint paint;

        public ViewHolder(View convertView) {
            parentLayout = convertView.findViewById(R.id.comment_parentlayout);
            userImg = (CustomImageView) convertView.findViewById(R.id.comment_usericon);
            userName = (TextView) convertView.findViewById(R.id.comment_username);
            userRank = (CustomImageView) convertView.findViewById(R.id.comment_rank);
            ivHonourPic = convertView.findViewById(R.id.ivHonourPic);
            tvArmyGroupInfo = convertView.findViewById(R.id.tvArmyGroupInfo);
            rankname = (TextView) convertView.findViewById(R.id.comment_rank_name);
            commentTime = (TextView) convertView.findViewById(R.id.comment_time);
            commentZan = (TextView) convertView.findViewById(R.id.comment_zan);
            laudContainer = (FrameLayout) convertView.findViewById(R.id.fl_laud_container);
            message = (BiaoQinTextView) convertView.findViewById(R.id.comment_message);
            replyLayout = (LinearLayout) convertView.findViewById(R.id.comment_reply_layout);
            readAllText = (TextView) convertView.findViewById(R.id.comment_readall);
            lineview = convertView.findViewById(R.id.item_divider);
//            gameLayout.setOnClickListener(NormalCommentAdapter.this);
            parentLayout.setOnClickListener(NormalCommentAdapter.this);
            laudContainer.setOnClickListener(NormalCommentAdapter.this);
            readAllText.setOnClickListener(NormalCommentAdapter.this);
            userImg.setOnClickListener(NormalCommentAdapter.this);
            userName.setOnClickListener(NormalCommentAdapter.this);
//            ViewTreeObserver viewTreeObserver = message.getViewTreeObserver();
//            viewTreeObserver.addOnPreDrawListener(this);

            parentLayout.setOnLongClickListener(NormalCommentAdapter.this);

            paint = message.getPaint();
        }

//        @Override
//        public boolean onPreDraw() {
//            int width = message.getWidth();
//            TextPaint paint = message.getPaint();
//            float measureText = paint.measureText(message.getText().toString());
//            if (measureText > width * 8) {
//                readAllText.setVisibility(View.VISIBLE);
//            } else {
//                readAllText.setVisibility(View.GONE);
//            }
//            return true;
//        }


    }
}
